package com.wispx.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wispx.shortlink.admin.common.biz.user.UserContext;
import com.wispx.shortlink.admin.common.convention.exception.ClientException;
import com.wispx.shortlink.admin.common.enums.UserErrorCodeEnum;
import com.wispx.shortlink.admin.dao.entity.UserDO;
import com.wispx.shortlink.admin.dao.mapper.UserMapper;
import com.wispx.shortlink.admin.dto.req.UserLoginReqDTO;
import com.wispx.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.wispx.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.wispx.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.wispx.shortlink.admin.dto.resp.UserRespDTO;
import com.wispx.shortlink.admin.service.GroupService;
import com.wispx.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.wispx.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static com.wispx.shortlink.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static com.wispx.shortlink.admin.common.enums.UserErrorCodeEnum.USER_NAME_EXIST;
import static com.wispx.shortlink.admin.common.enums.UserErrorCodeEnum.USER_SAVE_ERROR;

/**
 * 用户接口实现层
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final GroupService groupService;

    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if(userDO == null){
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        UserRespDTO result = new UserRespDTO();
        BeanUtils.copyProperties(userDO,result);
        return result;
    }

    @Override
    public Boolean availableUsername(String username) {
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO requestParam) {
        if(!availableUsername(requestParam.getUsername())){
            throw new ClientException(USER_NAME_EXIST);
        }
        // 用户名做分布式锁就可以保证用户名唯一
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + requestParam.getUsername());
        if(!lock.tryLock()){
            throw new ClientException(USER_NAME_EXIST);
        }

        try{
            int insert = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
            if(insert < 1){
                throw new ClientException(USER_SAVE_ERROR);
            }
            userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
            groupService.saveGroup(requestParam.getUsername(),"default group");
        }catch (DuplicateKeyException ex){
            // 数据库中唯一索引异常
            throw new ClientException(USER_SAVE_ERROR);
        }finally {
            lock.unlock();
        }
    }

    @Override
    public void updateByUsername(UserUpdateReqDTO requestParam) {
        if(!Objects.equals(requestParam.getUsername(), UserContext.getUsername())){
            throw new ClientException("用户未登录");
        }
        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername());
        baseMapper.update(BeanUtil.toBean(requestParam, UserDO.class),updateWrapper);
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        Map<Object, Object> hasLoginMap = stringRedisTemplate.opsForHash().entries(USER_LOGIN_KEY + requestParam.getUsername());
        if(CollUtil.isNotEmpty(hasLoginMap)){
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录失败"));
            return new UserLoginRespDTO(token);
        }
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword());
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if(userDO == null){
            throw new ClientException("登录失败请检查用户名或密码");
        }
        /* *
         * Key: 用户名
         * Value:
         *   key: token
         *   value: 用户信息 （防止重复登录）
         */
        String token = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash()
                .put(USER_LOGIN_KEY + requestParam.getUsername(),token,JSONUtil.toJsonStr(userDO));
        stringRedisTemplate.expire(USER_LOGIN_KEY + requestParam.getUsername(),30L, TimeUnit.MINUTES);
        return new UserLoginRespDTO(token);
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY + username,token) != null;
    }

    @Override
    public void logout(String username, String token) {
        if(!checkLogin(username,token)){
            throw new ClientException("用户名或Token不正确");
        }
        stringRedisTemplate.delete(USER_LOGIN_KEY + username);
    }
}
